package com.rykj.base.refreshview.impl;

import com.rykj.api.ApiFailAction;
import com.rykj.base.refreshview.data.IDataSource;
import com.rykj.util.RxUtil;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.CompositeSubscription;

/**
 * Description: author: zhangsan on 2017/8/16 下午3:28.
 */

public abstract class RxDataSource<Data> implements IDataSource<Data> {


//    protected ApiService apiService;

    protected CompositeSubscription mCompositeSubscription;


//    public RxDataSource(ApiService apiService) {
//        this.apiService = apiService;
//    }

    @Override
    public void requestData(int loadAction, IDataSourceResultHandler<Data> handler) {
        startRequest(loadAction, fetchData(loadAction, handler), handler);
    }

    @Override
    public void cancel() {
        unSubscribe();
    }

    protected void unSubscribe() {
        if (mCompositeSubscription != null) {
            mCompositeSubscription.unsubscribe();
        }
    }

    protected void startRequest(final int loadAction, Observable<Data> dataObservable, final IDataSourceResultHandler<Data> handler) {
        if (handler == null) {
            return;
        }
        Action1<Throwable> throwableAction1 = new ApiFailAction() {
            @Override
            public void call(Throwable throwable) {
                super.call(throwable);
                handler.handleError(throwable);
            }
        };
        Action1<Data> dataAction1 = new Action1<Data>() {
            @Override
            public void call(Data data) {
                handler.handleResult(loadAction, data);
            }
        };
        Subscription subscription = dataObservable.compose(RxUtil.<Data>normalSchedulers()).subscribe(dataAction1, throwableAction1);
        addSubscrebe(subscription);
    }

    protected abstract Observable<Data> fetchData(int loadType, IDataSourceResultHandler<Data> handler);

    protected void addSubscrebe(Subscription subscription) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscription);
    }
}
